<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<!-- <script>
    const arr = [1, 2, 3, 4]
    console.log('start')
    arr.forEach(item => {
        console.log(item)
    })
    console.log('end')
</script> -->
<script>
    Array.prototype.asyncForEach = async function (callback, args) {
        const _arr = this, // 因为调用的方式 [1,2,3].asyncForEach this指向数组
            isArray = Array.isArray(_arr), //判断调用者是不是数组
            _args = args ? Object(args) : window //对象化
        if (!isArray) {
            throw new TypeError("the caller must be a array type!")
        }
        for (let i = 0; i < _arr.length; i++) {
            await callback.call(_args,_arr[i])
        }
    }
    const sleep = (ms) => {
        return new Promise((resolve) => {
            setTimeout(resolve, ms)
        })
    }
    const arr = [
        () => console.log("start"),
        () => sleep(1000),
        () => console.log(1),
        () => sleep(1000),
        () => console.log(2),
        () => sleep(1000),
        () => console.log(3),
        () => sleep(1000),
        () => console.log("end")
    ]
    arr.asyncForEach(async(fn)=>{
        await fn()
    })
    // async function run(arr) {
    //     for (let i = 0; i < arr.length; i++) {
    //         await arr[i]()
    //     }
    // }
    //
    // run(arr)
</script>

</html>